import {InputNumber, List, Statistic} from "antd";
import {loadShoppingCarProducts} from "../../services/data";
import React, {useEffect, useState} from "react";
import {Checkbox, Stepper, Toast} from 'antd-mobile';
import "./shoppingCar.css"
import {useNavigate} from "react-router-dom";
import {ForbidFill, MinusCircleOutline, SmileFill, SmileOutline} from 'antd-mobile-icons'
import {getProductList} from "../../services/product";
const ShoppingCarCard=({updateCart,showDelete})=> {
    const navigate = useNavigate();

    const [productList, setProductList] = useState([]);
    const cart = JSON.parse(localStorage.getItem('cart')) || [];
    const productCount = JSON.parse(localStorage.getItem('productCount')) || {};

    useEffect(() => {
        fetchProductList();
    }, [productList]);
    //监听商品的变化，更新购物车，使其中商品与商品列表保持一致。
    useEffect(()=>{
        if (productList.length !== 0) {
            const updatedCart = cart.filter(cartItem => {
                const matchingProduct = productList.find(product => product.id === cartItem.id);
                if (matchingProduct) {
                    Object.assign(cartItem, matchingProduct);
                    return true; // 保留匹配到的项目
                }
                return false; // 过滤掉未匹配的项目
            });
            updateCart(updatedCart);
            localStorage.setItem('cart', JSON.stringify(updatedCart));
            //某商品删除后，如果重新上架，需要重新添加到购物车。
            if(productCount){
                const updateProductCount = {};
                for (const key in productCount) {
                    if (productList.some(product => product.id === parseInt(key))) {
                        updateProductCount[key] = productCount[key];
                    }
                }
                localStorage.setItem('productCount', JSON.stringify(updateProductCount));
            }

        }
    },[productList]);
    const fetchProductList = (page, pageSize) => {
        // 获取商品列表
        getProductList({ page: 1, pageSize: 10 }).then(response => {
            if (response && response.result) {
                setProductList(prevProductList =>{
                    return response.result;
                });

            } else {
                console.error('Error fetching product list: Invalid response');
            }
        }).catch(error => {
            console.error('Error fetching product list:', error);
        });

    };

    //通过id找到对应商品，改变单个购物车商品数量，更新到localstorage中，触发父组件中cart的更新
    const changeQuantity=(id,newCount)=>{
        console.log(id,newCount);
        const productCount = JSON.parse(localStorage.getItem('productCount'));
        const product = cart.filter((item)=>item.id === id);

        product[0].count = newCount;
        productCount[id] = newCount;
        localStorage.setItem('productCount',JSON.stringify(productCount));
        localStorage.setItem('cart',JSON.stringify(cart));
        updateCart(cart);
    };
    //通过id找到对应商品，更新其选中状态，更新到localstorage中，触发父组件中cart的更新
    const changeCheck=(id,checked)=>{
        const product = cart.filter((item)=>item.id === id);
        product[0].isChecked = checked;
        localStorage.setItem('cart',JSON.stringify(cart));
        updateCart(cart);
    };
    //删除购物车对应id的商品，同时将购物车对应id的商品数量从localStorage中删除，
    const deleteCartProduct=(id)=>{
        const updatedCart = cart.filter(item => item.id !== id);
        const productCount = JSON.parse(localStorage.getItem('productCount'));
        if(productCount && productCount[id]){
            delete productCount[id];
        }
        localStorage.setItem('productCount',JSON.stringify(productCount));
        localStorage.setItem('cart',JSON.stringify(updatedCart));
        updateCart(updatedCart);
    }
    //点击商品项，跳转到商品详情页
    const gotoProductDetails=(id)=>{
        navigate(`/product/${id}`);
    };
    return(
        <div>
           <List
               itemLayout="vertical"
               dataSource={cart}
               style={{
                   margin:"25px auto",
                   width:"98%",
               }}
               renderItem={(item,index)=>(
                   item.isShow && (
                           <List.Item
                               style={{
                                   margin:"20px auto",
                                   width:"98%",
                                   borderRadius:"13% 13% 13% 13% / 14% 14% 14% 14%",
                                   border:"1px solid rgba(212, 206, 206, 0.44)",
                                   backgroundColor:"white"
                               }}
                               extra={
                                   <Checkbox.Group
                                    >
                                       <Checkbox
                                           style={{
                                               marginLeft:"-380px",
                                               marginTop:"70px",
                                               display:"block"
                                           }}
                                           checked={item.isChecked}
                                           onChange={(e)=>{
                                               changeCheck(item.id,e);
                                           }}

                                       ></Checkbox>
                                       {showDelete &&<Checkbox
                                            icon={checked => {
                                                return <ForbidFill style={{ color: 'var(--adm-color-danger)' }} />;
                                            }}
                                            style={{
                                                marginLeft:"-380px",
                                                marginTop:"50px",
                                                display:"block"
                                            }}
                                            onClick={()=>{
                                                deleteCartProduct(item.id);
                                            }}
                                            >
                                        </Checkbox>}
                                   </Checkbox.Group>
                               }
                           >

                               <List.Item.Meta
                                   style={{
                                       margin:"15px 20px"
                                   }}
                                   avatar={<img src={item.details[0]} alt={item.productName} style={{width:"110px",height:"110px",marginLeft:"15px",marginRight:"10px"}}/>}
                                   title={item.productName}
                                   description={item.description}
                                   onClick={()=>{gotoProductDetails(item.id)}}

                               />

                               <div style={{width:"90px",marginLeft:"290px",marginTop:"-50px",border:"ipx solid red"}}>
                                   <Stepper style={{width:"80px"}} defaultValue={item.count} min={1} onChange={value => {
                                       changeQuantity(item.id,value)
                                   }}/>
                               </div>
                               <div style={{width:"80px",marginLeft:"150px",marginTop:"10px"}}>
                                   <Statistic value={'￥'+item.price} style={{color:'#FB5B40',textAlign:"center"}}/>
                               </div>

                           </List.Item>
                       )
               )}
           >
           </List>
            <div style={{ height:'90px'}}></div>
        </div>
    );
};
export default ShoppingCarCard;